package com.alibaba.citrus.cr.platform.enhance.functions.role;

import com.alibaba.citrus.cr.common.exception.FunctionException;
import com.alibaba.citrus.cr.common.util.SpringContextUtil;
import com.alibaba.citrus.cr.platform.enhance.repository.RoleRepository;
import com.alibaba.cz.base.model.enterprise.constant.RoleTypeEnum;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.RoleSDO;
import com.epoch.app.crplatformenhance.model.dto.QueryRoleRequest;
import lombok.Getter;
import lombok.Setter;

import java.util.List;
import java.util.UUID;

/**
 * @author zhoubc
 * @description: TODO
 * @date 2022/12/01 15:05
 */
public class RoleEntity {

    @Getter
    @Setter
    private RoleSDO sdo;

    private static RoleRepository roleRepository;

    static {
        roleRepository = SpringContextUtil.getBean(RoleRepository.class);
    }

    public static RoleEntity of(RoleSDO sdo) {
        RoleEntity entity = new RoleEntity();
        entity.setSdo(sdo);
        return entity;
    }

    public Result<String> doCreate() {
        QueryRoleRequest queryRoleRequest = new QueryRoleRequest();
        queryRoleRequest.setBelongOrganizationId(sdo.getBelongOrganizationId());
        queryRoleRequest.setType(RoleTypeEnum.FUNCTION.getNo());
        List<RoleSDO> roleSDOList = roleRepository.queryRoleList(queryRoleRequest);
        if (Nullable.stream(roleSDOList).anyMatch(roleSDO -> sdo.getName().equals(roleSDO.getName()))) {
            throw new FunctionException(ErrorMessage.code("OTS-01-001-02-15-002"));
        }
        sdo.setType(RoleTypeEnum.FUNCTION.getNo());
        if (sdo.getCode() == null) {
            sdo.setCode(UUID.randomUUID().toString().replace("-", ""));
        }
        return roleRepository.createRole(sdo);
    }

    public Result<Boolean> doEdit() {
        QueryRoleRequest queryRoleRequest = new QueryRoleRequest();
        queryRoleRequest.setBelongOrganizationId(sdo.getBelongOrganizationId());
        queryRoleRequest.setType(RoleTypeEnum.FUNCTION.getNo());
        List<RoleSDO> roleSDOList = roleRepository.queryRoleList(queryRoleRequest);
        if (Nullable.stream(roleSDOList).anyMatch(roleSDO -> sdo.getName().equals(roleSDO.getName()) && !sdo.getId().equals(roleSDO.getId()))) {
            throw new FunctionException(ErrorMessage.code("OTS-01-001-02-15-002"));
        }
        sdo.setType(RoleTypeEnum.FUNCTION.getNo());
        return roleRepository.updateRole(sdo);
    }

    public Result<Boolean> doRemove() {
        return roleRepository.removeRole(sdo);
    }

}
